package com.abc.robot01.activity

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Environment
import android.util.Base64
import android.util.Log
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.BasicText
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.abc.robot01.Base64QrCodeImage
import com.abc.robot01.R
import com.abc.robot01.answers
import com.abc.robot01.convertVectorToPng
import com.abc.robot01.questions
import com.abc.robot01.room.DatabaseContext
import com.abc.robot01.room.bean.ChatAnswerBean
import com.abc.robot01.room.bean.ChatQuestionBean
import com.abc.robot01.room.bean.CmdBean
import com.abc.robot01.vivemodel.LoginViewModel
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch

class LoginActivity : AppCompatActivity() {
    private val viewModel: LoginViewModel by viewModels()

    val  debug = false

    private fun requestStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED ||
            ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(
                this,
                arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ),
                0
            )
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestStoragePermission()


        viewModel.toastMessage.observe(this) { message ->
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
        }
//        convertVectorToPng(this,R.drawable.z1,Environment.getExternalStorageDirectory().toString()+"/vector_image.png")

        //新增问题
        if(debug) {
            lifecycleScope.launch(IO) {
                repeat(answers.size) {
                    val id = DatabaseContext.getCmdDao()
                        .addCmd(CmdBean().apply { name = "没有名字" })

                    //新增答案
                    val q1 = ChatAnswerBean().apply {
                        cmd_Id = id.toString()
                        ttsText = answers[it]
                    }
                    DatabaseContext.getChatAnswerDao().addAnswer(q1)
                    Log.e(TAG, "addAnswer $q1");

                    questions[it].split("/").forEach {
                        val q = ChatQuestionBean().apply {
                            cmd_id = "" + id
                            question = it
                        }
                        DatabaseContext.getChatQuestionDao().addQuestion(q)
                        Log.e(TAG, "addQuestion $q");
                    }
                }
            }
        }

        Log.e(TAG, "onCreate");
        viewModel.next.observe(this) {
            if(it) {
                finish()
                startActivity<Init> {}
            }
        }

        setContent {
            if ((viewModel.sn != "")) {
                Column(
                    verticalArrangement = Arrangement.Top,
                    horizontalAlignment = Alignment.CenterHorizontally,
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color.Black)
                        .padding(top = 143.px)
                ) {
                    BasicText(
                        modifier = Modifier.offset(y = 0.dp),
                        text = """
      欢迎使用"一束光科技"
  """.trimIndent(),
                        style = TextStyle(
                            fontWeight = FontWeight.Normal,
                            fontSize = 42.mysp,
                            color = Color.White,
                        ),
                    )
                    Spacer(modifier = Modifier.height(100.px))
                    Base64QrCodeImage(viewModel.base64)

                    Spacer(modifier = Modifier.height(100.px))
                    BasicText(
                        modifier = Modifier.offset(y = 0.dp),
                        text =
                        "本机SN码为" + viewModel.sn,
                        style = TextStyle(
                            fontWeight = FontWeight.Normal,
                            fontSize = 30.mysp,
                            color = Color.White,
                        ),
                    )
                    if (viewModel.debug) {
                        Text(
                            text = "Count: ${viewModel.count}",
                            style = MaterialTheme.typography.headlineMedium,
                            color = Color.White
                        )
                    }
                }
            }
        }
    }

    companion object {
        val TAG = "LoginActivity"
    }
}
